// 按钮方法
export function initButton(vm) {
  return {
    handleReset() {
      vm.resetDraggableZIndex()
      vm.customButtons = [
        {
          text: "取消",
          action: () => vm.$refs.messageBox.close(),
          type: "",
        },
        {
          text: "确定",
          action: () => {
            vm.$refs.messageBox.close();
            vm.mapLoading = true;
            vm.canvasrResetData();
          },
          type: "primary",
        },
      ];
      vm.messageBoxtitle = "确定重置您的所有操作吗?";
      vm.$refs.messageBox.open();
    },
    handleCancel() {
      vm.resetDraggableZIndex()
      vm.customButtons = [
        {
          text: "取消",
          action: () => vm.$refs.messageBox.close(),
          type: "",
        },
        {
          text: "确定",
          action: () => {
            vm.$message({
              type: "success",
              message: "已取消保存",
            });
            vm.$refs.messageBox.close();
            setTimeout(() => {
              const query = {};
              if (vm.isChild) {
                query.buildingId = vm.buildingId;
              }
              vm.$router.push({
                path: "/pavilion/floor",
                query: {
                  ...query,
                },
              });
            }, 200);
          },
          type: "primary",
        },
      ];
      vm.messageBoxtitle = "确定取消所有操作并返回上一页吗?";
      vm.$refs.messageBox.open();
    },
    handleSave() {
      vm.resetDraggableZIndex()
      const floorPosIds = vm.floorPoint.map((item) => item.posId);
      const currentPosIds = vm.allObjects.map((item) => item.posId || "");
      // 找出被删除的 posId（存在于 floorPosIds 但不在 currentPosIds 中）
      const deletedPosIds = floorPosIds.filter(
        (posId) => !currentPosIds.includes(posId)
      );
      // 判断是否有删除的对象
      const hasDeleted = deletedPosIds.length > 0;

      // 处理特殊情况：floorPoint 为空（全新添加）
      if (vm.floorPoint.length === 0) {
        vm.customButtons = [
          {
            text: "取消",
            action: () => vm.$refs.messageBox.close(),
            type: "",
          },
          {
            text: "保存",
            action: () => vm.saveloadLowLarDa(true),
            type: "primary",
          },
        ];
        vm.messageBoxtitle = "确定保存所有新增点位吗?";
        vm.$refs.messageBox.open();
        return;
      }
      if (hasDeleted) {
        vm.customButtons = [
          {
            text: "取消",
            action: () => vm.$refs.messageBox.close(),
            type: "",
          },
          {
            text: "删除并保存",
            action: () => vm.saveloadLowLarDa(false),
            type: "danger",
          },
          {
            text: "回退并保存",
            action: () => vm.saveloadLowLarDa(true),
            type: "primary",
          },
        ];
        vm.messageBoxtitle = `检测到${deletedPosIds.length}个已删除点位，请确认保存方式`;
        // 打开确认框
        vm.$refs.messageBox.open();
      } else {
        vm.customButtons = [
          {
            text: "取消",
            action: () => vm.$refs.messageBox.close(),
            type: "",
          },
          {
            text: "保存",
            action: () => vm.saveloadLowLarDa(true),
            type: "primary",
          },
        ];
        vm.messageBoxtitle = "确定保存吗?";
        // 打开确认框
        vm.$refs.messageBox.open();
      }
    },
    saveloadLowLarDa(flage) {
      if (!flage) {
        vm.$confirm("此操作将永久删除业务点位信息, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            vm.goNext(flage);
          })
          .catch(() => {
            vm.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        vm.goNext(flage);
      }
    },
    goNext(flage) {
      if (vm.checkPosNoDuplication()) {
        vm.saveLoad = true;
        // console.log("所有对象信息:", vm.allObjects);
        const arr = vm.dealPositionInfo();
        // console.log("所有点位信息:", arr);
        vm.requesteditOrAddPoint(arr, flage);
      } else {
        vm.$message({
          message: "编号有重复，请检查后重新保存！",
          type: "error",
        });
      }
    },
    // 处理对象点位信息
    dealPositionInfo() {
      // console.log(vm.allObjects, "allObjects");
      const arr = [];
      if (vm.allObjects.length > 0) {
        vm.allObjects.forEach((item, index) => {
          // console.log(item, "item");
          const config = vm.dealConfigInfo(item);
          const obj = {
            posId: "", // 新增为空，修改为对应id
            posNo: item.posNo,
            posName: item.text,
            x: item.x,
            y: item.y,
            h: item.height,
            w: item.width,
            r: item.angle,
            type: item?.type ?? "Shelf", // 后面可以通过下拉框选择对应的枚举
            model: item?.imgtarget?.modelId,
            mapId: vm.mapId,
            config: config,
            tags: item.tags,
          };
          // 修改的时候需要带上 posId
          if (item.posId) {
            obj.posId = item.posId;
          }
          if (item.posNo) {
            obj.posNo = item.posNo;
          }
          arr.push(obj);
        });
      }
      return arr;
    },
    // 处理config信息
    dealConfigInfo(item) {
      let result;
      const obj = item.configForm;
      // console.log(obj, "obj");
      const configArr = vm.ConfigType.find(
        (tig) => tig.name === item.type
      ).value;
      if (obj) {
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            configArr.forEach((item) => {
              if (item.name === key) {
                if (item.type === "imageUpload") {
                  // 对于图片上传，若是需求单一图片则取集合的第一张（总共也就一张）
                  if (item.valueType === "number") {
                    obj[key] = obj[key][0];
                  }
                }
              }
            });
          }
        }
        delete obj.allObjectsid;
        delete obj.imageOidListurl;
        delete obj.vrImageOidurl;
        // obj.imageOidList = []; // 强制清空选择
        // obj.vrImageOid = ""
        result = JSON.stringify(obj);
      } else {
        result = "";
      }
      return result;
    },
  };
}
